package cn.lcfms.app;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import cn.lcfms.bin.core.Application;
public class BaseController {
	/**
	 * 该方法将在执行控制器之前被执行
	 */
    protected void beforeProtected(HttpServletRequest request,HttpServletResponse response){   	 	
    	if(Application.APP_PATH.equals("")) {
    		boolean b=Application.config("nginx.on");
    		if(b) {
    			String url=Application.config("nginx.url");
    			Application.APP_PATH = url;
    		}else {
    			String contextPath = request.getContextPath();
        	    if(request.getServerPort()==80){
        	    	Application.APP_PATH = request.getScheme()+"://"+request.getServerName()+contextPath+"/";
        	    }else{
        	    	Application.APP_PATH = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+contextPath+"/";
        	    }	
    		}		
    	}  	
	    request.setAttribute("APP", Application.APP_PATH); 		    
	    request.setAttribute("VERSION", Application.VERSION); 		    
    }  
    /**
   	 * 该方法将在执行控制器之后，调入模板之前被执行
     * @throws IOException 
   	 */
    protected void afterProtected(HttpServletRequest request,HttpServletResponse response,ModelAndView view) throws IOException{  	    	
    	if(view!=null && view.getViewName()!=null){	
    		String viewname=view.getViewName();	 
			if(viewname.startsWith("[") && viewname.endsWith("]")){
				response.setContentType("application/json;charset=utf-8");
				PrintWriter writer = response.getWriter();
	    		writer.write(viewname);
	    		writer.flush();
	    		writer.close();
	    		view.clear();
			}
			if(viewname.startsWith("{") && viewname.endsWith("}")){
				response.setContentType("application/json;charset=utf-8");
				PrintWriter writer = response.getWriter();			
				if(viewname.indexOf("\"")==-1) {
					StringBuffer buffer=new StringBuffer("{");
					viewname=viewname.substring(1, viewname.length()-1);
					String[] split = viewname.split(",");
					for(int i=0;i<split.length;i++) {
						String str=split[i];
						int index=str.indexOf(":");
						int length=str.length();
						buffer.append("\""+str.substring(0, index)+"\":\""+str.substring(index+1, length)+"\"");
						if(i!=split.length-1) {
							buffer.append(",");
						}			
					}	
					buffer.append("}");
					viewname=buffer.toString();
				}
				writer.write(viewname);
	    		writer.flush();
	    		writer.close();
	    		view.clear();
			}
			if(viewname.startsWith("<?xml") && viewname.endsWith(">")){
				response.setContentType("application/xml;charset=utf-8");
				PrintWriter writer = response.getWriter();
	    		writer.write(viewname);
	    		writer.flush();
	    		writer.close();
	    		view.clear();
			}
		}
    }
}
